package com.yhsimon.rabbitmq.work.round;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Work1 {
    public static void main(String[] args) {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setVirtualHost("/");
        connectionFactory.setHost("192.168.100.128");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");

        Connection connection=null;
        Channel channel=null;
        try {
            connection = connectionFactory.newConnection("Work1");

            channel=connection.createChannel();

            Channel finalChannel=channel;

            finalChannel.basicConsume("queue-work-round", true, new DeliverCallback() {
                @Override
                public void handle(String consumerTag, Delivery message) throws IOException {
                    try {
                        System.out.println("Work-1收到的消息是：" + new String(message.getBody(), "UTF-8"));
                        Thread.sleep(2000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, new CancelCallback() {
                @Override
                public void handle(String consumerTag) throws IOException {

                }
            });
            System.out.println("Work-1开始接收消息");
            System.in.read();
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("接收消息出现异常");
        }finally {
            if(channel!=null&&channel.isOpen()){
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if(connection!=null&&connection.isOpen()){
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
